package com.xx.permission.config;

import com.alibaba.fastjson.JSONArray;
import com.xx.permission.entity.result.DataPermission;
import com.xx.permission.entity.result.RoleDataPermission;
import com.xx.permission.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author aqi
 * @since 2023/5/18 14:48
 * @describe 初始化配置数据
 */
@Slf4j
@Component
public class InitConfig {

    @Resource
    private SysRoleService sysRoleService;

    @PostConstruct
    public void init() {
        this.initRoleDataPermission();
    }

    /**
     * 初始化角色数据权限
     */
    private void initRoleDataPermission() {
        log.info("初始化角色数据权限...");
        List<RoleDataPermission> roleDataPermission = sysRoleService.getRoleDataPermission();
        for (RoleDataPermission dataPermission : roleDataPermission) {
            List<DataPermission> dataPermissions = JSONArray.parseArray(dataPermission.getDataPermission(), DataPermission.class);
            dataPermission.setDataPermissionList(dataPermissions);
        }
        CacheData.ROLE_DATA_PERMISSION_LIST = roleDataPermission;
        CacheData.ROLE_DATA_PERMISSION_MAP = CacheData.ROLE_DATA_PERMISSION_LIST.stream()
                .collect(Collectors.groupingBy(RoleDataPermission::getRoleId));
    }

}
